import ajax from "./promiseAjax.js";

let token = sessionStorage.getItem("token");
let chooseListApi = "http://newshopapi.0melon0.cn/api/f_user/chooselist";
let chooseDayApi = "http://newshopapi.0melon0.cn/api/f_user/chooseday";

let chooseList = document.querySelector(".layui-form");
let chooseList1 = chooseList.querySelector("select")
let listBody = document.querySelector(".list>.body");
let chooseListData = {
  "token": token,
}

//获取预约时间列表并渲染到下拉框中
ajax(chooseListApi, chooseListData, "GET").then(res => {
  // console.log(res.result.list[0].day_time);
  res.result.list.forEach((item) => {
    chooseList1.innerHTML += `"<option>${item.day_time}</option>"}`;
  })

  //渲染列表里的第一天的场次
  listRender(chooseList1.children[0].value);
})

//场次及状态渲染到列表中
chooseList1.addEventListener("change", () => {
  listBody.innerHTML = "";
  listRender(chooseList1.value);
})

//封装场次列表渲染以及sessions会话存储代码
function listRender(dayTimeData) {
  let chooseDayData = {
    "token": token,
    "day_time": dayTimeData
  }
  ajax(chooseDayApi, chooseDayData, "GET").then(res => {
    res.result.list.forEach((item) => {
      //获取各个场次开始时间的时间戳
      let endTime = new Date(`${dayTimeData} ${item.show_name.substr(0, 5)}`).getTime();
      //判断场次是否可以预约
      if (Date.now() - endTime > 0) {
        listBody.innerHTML += `
        <div class="box">
        <div class='sessions'>${item.show_name}</div>
        <div class='status red'>已约满</div>
        </div>
        `;
      } else {
        listBody.innerHTML += `
        <div class="box">
        <div class='sessions'>${item.show_name}</div>
        <div class='status green'>可预约</div>
        </div>
        `;
      }
    })
  }).then(() => {
    let box = listBody.querySelectorAll(".box");
    box.forEach((item, index) => {
      item.addEventListener("click", () => {
        if (item.lastElementChild.innerHTML == "可预约") {
          // console.log(item.firstElementChild.innerHTML.substr(0,5));
          sessionStorage.setItem("completeTime", item.firstElementChild.innerHTML);
          sessionStorage.setItem("startTime", item.firstElementChild.innerHTML.substr(0, 5));
          //存储show_id和day_time
          ajax(chooseDayApi, chooseDayData, "GET").then(res => {
            sessionStorage.setItem("day_time", chooseList1.value);
            sessionStorage.setItem("show_id", res.result.list[index].show_id);
            //跳转到预约成功后的二维码页面
            location.href = "bookingSuccess.html";
          })
        }
      })
    })
  })
}






